package evostar.service;

import evostar.dao.OrderDAO;
import evostar.model.OrderInfo;
import evostar.model.SeckillOrder;
import evostar.model.User;
import evostar.VO.GoodsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class OrderService {
    @Autowired
    private OrderDAO orderDAO;
    @Autowired
    private RedisService redisService;

    private static final String OrderInfo = "orderInfo_";//orderInfo_userId_goodsId

    public OrderInfo getSeckillOrderByUserIdGoodsId(int userId, int goodsId) {
        return redisService.getValue(OrderInfo + userId + "_" + goodsId, OrderInfo.class);
    }


    @Transactional
    public OrderInfo createOrder(User user, GoodsVO goods) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateDate(new Date());
        orderInfo.setGoodsCount(1);
        orderInfo.setGoodsId(goods.getId());
        orderInfo.setGoodsName(goods.getGoodsName());
        orderInfo.setUserId(user.getId());
        orderInfo.setGoodsPrice(goods.getGoodsPrice());
        orderInfo.setStatus(0);
        //添加数据
        int orderId = orderDAO.insert(orderInfo);
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setGoodsId(goods.getId());
        seckillOrder.setOrderId(orderId);
        seckillOrder.setUserId(user.getId());
        orderDAO.inserSeckillOrder(seckillOrder);

        redisService.setValue(OrderInfo + user.getId() + "_" + goods.getId(), orderInfo, 0);
        return orderInfo;
    }
}
